<script lang="ts" setup>
import type { Location } from '#/api';

import { computed, ref, watch } from 'vue';

import { useVbenModal } from '@vben/common-ui';

import { Button } from 'ant-design-vue';

import { useVbenForm } from '#/adapter/form';
import {
  addLocation,
  setBatchMixing,
  setProductMixing,
  updateLocation,
} from '#/api';

import { confirm, messageSuccess } from '../common/common';
import { useSchema } from './data';

const emit = defineEmits(['success']);
const formData = ref<Location.Row>();
const title = ref<string>();

const showConfrimBtn = ref(true);
const [Form, formApi] = useVbenForm({
  commonConfig: {
    // 所有表单项
    componentProps: {
      class: 'w-full',
    },
  },
  layout: 'horizontal',
  schema: useSchema(),
  showDefaultActions: false,
});

const getTitle = computed(() => {
  if (formData.value?.attr1 === '1') return '查看库区设置';
  return formData.value?.attr1 === '2' ? '编辑库区设置' : '新增库区设置';
});
watch(getTitle, (newTitle) => {
  title.value = newTitle;
});

const [Modal, modalApi] = useVbenModal({
  closeOnClickModal: false,
  destroyOnClose: true,
  async onConfirm() {
    const { valid } = await formApi.validate();
    if (valid) {
      modalApi.lock();

      let data;
      await formApi.getValues().then((res) => {
        data = res;
      });
      try {
        await (formData.value?.locationId
          ? updateLocation(data!)
          : addLocation(data!));
        modalApi.close();
        emit('success', formData.value?.locationId ? '修改成功' : '新增成功');
      } finally {
        modalApi.lock(false);
      }
    }
  },
  onOpenChange(isOpen) {
    if (isOpen) {
      const data = modalApi.getData<Location.Row>();
      if (data) {
        formData.value = data;
        formApi.setValues(formData.value);
        showConfrimBtn.value = formData.value?.attr1 !== '1';
        modalApi.setState({
          showConfirmButton: showConfrimBtn.value,
        });
      }
    }
  },
});

function resetForm() {
  formApi.resetForm();
  formApi.setValues({});
}
/**
 * 提交表单后的处理函数
 * @param {string} msg - 提交成功后的提示信息
 */
function handleSubmit(msg: string) {
  messageSuccess(msg);
}

/* 重置产品混放规则 */
async function productMixingChange(status) {
  try {
    await confirm(`确认要重置库区下所有库位的产品混放规则吗？`, '系统提示');
    await setProductMixing({
      locationId: formData.value?.locationId,
      flag: status === 'Y' ? 'true' : 'false',
    });
    emit('success', '设置成功');
  } catch (error) {
    console.error('操作失败', error);
  }
}
/* 重置批次混放规则 */
async function batchMixingChange(status) {
  try {
    await confirm(`确认要重置库区下所有库位的批次混放规则吗？`, '系统提示');
    await setBatchMixing({
      locationId: formData.value?.locationId,
      flag: status === 'Y' ? 'true' : 'false',
    });
    emit('success', '设置成功');
  } catch (error) {
    console.error('操作失败', error);
  }
}
</script>

<template>
  <Modal :title="getTitle">
    <Form class="mx-4" @success="handleSubmit">
      <template #productMixing>
        <el-tooltip
          class="box-item"
          content="点击按钮设置此库区下所有库位允许产品混放。"
          placement="top-start"
        >
          <el-button
            type="primary"
            plain
            size="small"
            @click="productMixingChange('Y')"
          >
            允许
          </el-button>
        </el-tooltip>
        <el-tooltip
          class="box-item"
          content="点击按钮设置此库区下所有库位不允许产品混放。"
          placement="top-start"
        >
          <el-button
            type="danger"
            plain
            size="small"
            @click="productMixingChange('N')"
          >
            不允许
          </el-button>
        </el-tooltip>
      </template>
      <template #batchMixing>
        <el-tooltip
          class="box-item"
          content="点击按钮设置此库区下所有库位允许批次混放。"
          placement="top-start"
        >
          <el-button
            type="primary"
            plain
            size="small"
            @click="batchMixingChange('Y')"
          >
            允许
          </el-button>
        </el-tooltip>
        <el-tooltip
          class="box-item"
          content="点击按钮设置此库区下所有库位不允许批次混放。"
          placement="top-start"
        >
          <el-button
            type="danger"
            plain
            size="small"
            @click="batchMixingChange('N')"
          >
            不允许
          </el-button>
        </el-tooltip>
      </template>
    </Form>
    <template #prepend-footer>
      <div class="flex-auto" v-if="showConfrimBtn">
        <Button type="primary" danger @click="resetForm"> 重置 </Button>
      </div>
    </template>
  </Modal>
</template>
